package com.jun.admin.core.config;

import cn.hutool.core.map.MapUtil;
import com.jun.sso.core.conf.Conf;
import com.jun.sso.core.user.XxlSsoUser;
import com.jun.sso.core.util.JedisUtil;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //解析token，获取user信息
        Map<String, List<String>> headers = request.getHeaders();
        String storeKey = parseStoreKey(MapUtil.get(headers, "cookie", String.class, null));
        if (storeKey != null) {
            XxlSsoUser xxlUser = (XxlSsoUser)JedisUtil.getObjectValue(Conf.SSO_SESSIONID + "#" + storeKey);
            //将session存起来
            Map<String, Object> userProperties = sec.getUserProperties();
            userProperties.put(HttpSession.class.getName(), xxlUser.getUserid());
        }
    }

    public static String parseStoreKey(String sessionId) {
        String[] split = sessionId.split("=");
        sessionId = split[1];
        if (sessionId!=null && sessionId.indexOf("_")>-1) {
            String[] sessionIdArr = sessionId.split("_");
            if (sessionIdArr.length==2
                    && sessionIdArr[0]!=null
                    && sessionIdArr[0].trim().length()>0) {
                String userId = sessionIdArr[0].trim();
                return userId;
            }
        }
        return null;
    }
}
